package com.yootk.provider.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yootk.common.dto.DeptDto;
import com.yootk.common.util.DeepBeanUtils;
import com.yootk.provider.dao.IDeptDao;
import com.yootk.provider.vo.Dept;
import com.yootk.service.IDeptService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class DeptServiceImpl implements IDeptService {

    @Autowired
    private IDeptDao deptDao;

    @Override
    public DeptDto get(long id) {
        DeptDto dto = new DeptDto();
        // 在本地端通过了VO类实现了数据的加载，随后将此数据拷贝到DTO对象之中
        BeanUtils.copyProperties(deptDao.selectById(id), dto);
        return dto;
    }

    @Override
    public boolean add(DeptDto dto) {
        Dept dept = new Dept();
        BeanUtils.copyProperties(dto, dept);
        return deptDao.insert(dept) > 0;
    }

    @Override
    public List<DeptDto> list() {
        QueryWrapper<Dept> wrapper = new QueryWrapper<>();
        List<DeptDto> allDepts = DeepBeanUtils.copyListProperties(
                deptDao.selectList(wrapper), DeptDto::new); // 集合数据拷贝
        return allDepts;
    }

    @Override
    public Map<String, Object> split(int currentPage, int lineSize, String column, String keyword) {
        QueryWrapper<Dept> wrapper = new QueryWrapper<>();
        wrapper.like(column, keyword);  // 模糊查询
        int count = deptDao.selectCount(wrapper);   // 统计个数
        Page<Dept> page = deptDao.selectPage(new Page<>(currentPage, lineSize, count), wrapper);
        Map<String, Object> map = new HashMap<>();  // 包装返回结果
        map.put("allDepts", DeepBeanUtils.copyListProperties(page.getRecords(), DeptDto::new));
        map.put("allRecorders", page.getTotal());
        map.put("allPages", page.getPages());
        return map;
    }
}
